package item.lxp.controller;


import item.lxp.Util.ValidatorUtil;
import item.lxp.configuation.UserConfiguation;
import item.lxp.entity.User;
import item.lxp.execption.CaseExceptin;
import item.lxp.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.awt.print.Pageable;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController {


    //  查找 get  新增 post 修改 put 删除 delete
    //  配置数据库连接池
    //  接口文档
    //  日志

    @Autowired
    JdbcTemplate jdbcTemplate;

    // 使用 mybatis
    @Autowired
    public UserMapper userMapper;

    @Autowired
    public UserConfiguation userConfiguation;


    /*查单条*/
    @GetMapping (value = {"/{id}"})
    public User find(@PathVariable(value ="id")  Long id){

        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);

        User user =jdbcTemplate.queryForObject("select * from user where user_id =? ",rowMapper, id);

        return user;
    }

    @GetMapping
    public List<User> list(@PageableDefault(size = 1 ,page = 10 ,sort = "user_id",direction = Sort.Direction.ASC) Pageable pageable){

        //  可以使用 @RequestParam 来获取参数 ，默认该参数必填

        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);

        List<User> user =jdbcTemplate.query("select * from user",rowMapper);

        return user;
    }

    @PostMapping
    public String insert(@RequestBody @Valid User user, BindingResult bindingResult){


        List<ObjectError> allErrors = bindingResult.getAllErrors();
        allErrors.forEach(e -> System.out.println(e.getDefaultMessage()));


        jdbcTemplate.update("insert into user (openid ,nickname,sex,province,city,country,headimgurl,mobile,created_time,price) value ( ?, ?, ?, ?, ?, ?, ?, ?, ?,?)",new Object[]{
                user.getOpenid(),user.getNickname(),user.getSex(),user.getProvince(),user.getCity(),user.getCountry(),
                user.getHeadimgurl(),null,null,user.getPrice()
        });
        return "success";
    }

    @PutMapping
    public String update(@RequestBody User user){

        jdbcTemplate.update("update user set openid = ? where user_id = ?",new Object[]{user.getOpenid() ,user.getUserId() });

        return "success";
    }

    @DeleteMapping("/{id}")
    public User delete(@PathVariable(value = "id") Integer id){

        // 关闭jdbc 连接 Spring 中默认是自动关闭
        // jdbcTemplate.getDataSource().getConnection().close();

        User user = userMapper.selectByPrimaryKey(id);

        user.setOpenid(null);

        System.out.println(userConfiguation.getAge());
        System.out.println(userConfiguation.getName());

        try {
            ValidatorUtil.validate(user);
        }catch(Exception e){
            throw new CaseExceptin("内部错误","200");
        }

        return user;
    }

}
